package com.etlmaster.executor.processors.File;

import org.apache.commons.vfs2.AllFileSelector;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;

import com.etlmaster.executor.utils.DpVfsUtils;
import com.etlmaster.executor.utils.LogWriter;

/**
 * 文件操作帮助类
 * 
 * @author Wugf
 * @date 2016-03-08
 */
public class FileHelper {
	public static boolean deleteFileObject(FileObject file)
			throws FileSystemException {
		if (file.getType() == FileType.FILE) {
			file.delete();
		} else if (file.getType() == FileType.FOLDER) {
			LogWriter.addLog("INFO", "目标文件对象为文件夹，将删除整个文件夹");
			AllFileSelector fs = new AllFileSelector();
			file.delete(fs);
		} else {
			LogWriter.addLog("ERROR", "不支持的文件类型：{}", file.getType().toString());
			return false;
		}
		return true;
	}

	private static void moveFileObject(FileObject sourceFile, FileObject newFile)
			throws FileSystemException {
		newFile.createFile();
		sourceFile.moveTo(newFile);
	}

	public static boolean moveAndCheckResult(String souceFileUri,
			String newFileUri) {
		FileObject file = null;
		FileObject newfile = null;
		try {

			file = DpVfsUtils.getInstance().resolveFile(souceFileUri);
			newfile = DpVfsUtils.getInstance().resolveFile(newFileUri);

			if (file.canRenameTo(newfile)) {
				moveFileObject(file, newfile);
			} else {
				LogWriter.addLog("ERROR", "路径{}与{}不在一个文件系统不能移动或改名",
						souceFileUri, newFileUri);

			}
		} catch (Exception e) {
			LogWriter.addLog("ERROR", "移动文件{}到 {} 失败,{}", souceFileUri,
					newFileUri, e.getMessage());
			return false;
		} finally {
			DpVfsUtils.getInstance().closeFileObject(file);
			DpVfsUtils.getInstance().closeFileObject(newfile);
		}
		return true;
	}

}
